package com.jin.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.jin.common.to.es.SkuEsModel;
import com.jin.gulimall.search.config.GulimallElasticsearchConfig;
import com.jin.gulimall.search.constant.EsConstant;
import com.jin.gulimall.search.service.SearchService;
import com.jin.gulimall.search.vo.SearchParm;
import com.jin.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Resource
    private RestHighLevelClient client;

    //去es进行检索
    @Override
    public SearchResult search(SearchParm searchParm) {
        SearchResult searchResult=null;
        //通过请求参数构建查询请求
        SearchRequest request = bulidSearchRequest(searchParm);
        try {
            //执行
            SearchResponse searchResponse = client.search(request, GulimallElasticsearchConfig.COMMON_OPTIONS);
            //将es响应数据封装成结果
            searchResult=bulidSearchResult(searchParm, searchResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResult;
    }

    private SearchResult bulidSearchResult(SearchParm param, SearchResponse response) {
        SearchResult searchResult = new SearchResult();
        SearchHits hits = response.getHits();
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        for (SearchHit hit : hits.getHits()) {
            String sourceAsString = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
            //这里直接封装的skuTitle没有高亮，需要自己重新再次封装
            if(!StringUtils.isEmpty(param.getKeyword())){
                HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                String string = skuTitle.getFragments()[0].string();
                skuEsModel.setSkuTitle(string);
            }
            skuEsModels.add(skuEsModel);
        }
        //1.返回的所有查询到的商品
        searchResult.setProducts(skuEsModels);

        //以下的三个信息时聚合的内容
        //2.当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            long attrId = bucket.getKeyAsNumber().longValue();
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            attrVo.setAttrId(attrId);
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attr_value_agg.getBuckets().stream().map(item -> {
                String keyAsString = item.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);
        //3.当前所有商品涉及到的所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brandAggBuckets = brand_agg.getBuckets();
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            long brandId = brandAggBucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);
            ParsedStringTerms brand_img_agg = brandAggBucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            ParsedStringTerms brand_name_agg = brandAggBucket.getAggregations().get("brand_name_agg");
            String brandName = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brandVo.setBrandName(brandName);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);
        //4.当前所有商品涉及到的所有分类信息
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            Long key = (Long) bucket.getKey();
            catalogVo.setCatalogId(key);
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);

        //5.分页信息-页码
        searchResult.setPageNum(param.getPageNum());
        //6.分页信息-总记录数
        long total = hits.getTotalHits().value;
        searchResult.setTotal(total);
        //7.分页信息-总页码
        int pages = (int)total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int)total / EsConstant.PRODUCT_PAGESIZE : ((int)total / EsConstant.PRODUCT_PAGESIZE + 1);
        searchResult.setTotalPages(pages);
        //设置导航可以检索的页码
        List<Integer> pageNavs = new ArrayList<>();
        for(int i=1;i<=pages;i++){
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);
        return searchResult;
    }

    private SearchRequest bulidSearchRequest(SearchParm searchParm) {
        //用于构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //1.构建bool query
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //1.1 bool must
        if(!StringUtils.isEmpty(searchParm.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParm.getKeyword()));
        }
        //1.2
        //1.2.1 catalog
        if(searchParm.getCatalog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", searchParm.getCatalog3Id()));
        }
        //1.2.2 brand
        if(searchParm.getBrandId()!=null&&searchParm.getBrandId().size()>0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", searchParm.getBrandId()));
        }
        //1.2.3 hasStock
        if(searchParm.getHasStock()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", searchParm.getHasStock() == 1));
        }
        //1.2.4 skuPrice
        // 1_500/_500/500_
        if(!StringUtils.isEmpty(searchParm.getSkuPrice())){
            RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("skuPrice");
            String[] s = searchParm.getSkuPrice().split("_");
            if(s.length==2){
                rangeQueryBuilder.gte(s[0]).lte(s[1]);
            }else if(s.length==1){
                if(searchParm.getSkuPrice().startsWith("_")){
                    rangeQueryBuilder.gte(s[0]);
                }
                if(searchParm.getSkuPrice().endsWith("_")){
                    rangeQueryBuilder.lte(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }
        //1.2.5按照所有指定的属性进行查询
        if(searchParm.getAttrs()!=null&&searchParm.getAttrs().size()>0){
            for (String attrStr : searchParm.getAttrs()) {
                BoolQueryBuilder nestedboolQuery = QueryBuilders.boolQuery();
                //attr=1_5寸:8寸
                String[] s = attrStr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestedboolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedboolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //每一个必须都得生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedboolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
        }

        //2.sort eg:sort=saleCount_desc/asc
        if(!StringUtils.isEmpty(searchParm.getSort())){
            String[] split = searchParm.getSort().split("_");
            sourceBuilder.sort(split[0], split[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC);
        }
        //3.分页  检测结果分页
        if(searchParm.getPageNum()!=null){
            sourceBuilder.from((searchParm.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
            sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        }


        //4.高亮highlight
        if(!StringUtils.isEmpty(searchParm.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        sourceBuilder.query(boolQueryBuilder);

        //品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        TermsAggregationBuilder brand_name_agg = AggregationBuilders.terms("brand_name_agg");
        brand_name_agg.field("brandName").size(1);
        //品牌的子聚合
        brand_agg.subAggregation(brand_name_agg);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        //TODO: 1.聚合brand
        sourceBuilder.aggregation(brand_agg);
        //2.分类聚合 catalog_agg
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(10);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(10));
        //TODO: 2.聚合catalog
        sourceBuilder.aggregation(catalog_agg);
        //属性聚合 attr_agg
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        //聚合出当前所有的attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //聚合分析出当前attr_id对应的名字
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue"));
        attr_agg.subAggregation(attr_id_agg);
        //TODO: 3.聚合attr
        sourceBuilder.aggregation(attr_agg);
        String s = sourceBuilder.toString();
        System.out.println("构建的DSL"+s);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }
}


